import React, { Component } from 'react';
import {
  View, Text, StyleSheet, TouchableOpacity, Image, TextInput,
  PixelRatio, Platform, ScrollView, Modal, FlatList, Alert
} from 'react-native';
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
// import { productSelectStyle } from '../_common/style';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';

const scale = GLOBAL.SCALE;
let optionPicSourse = require('../../../../imgs/global/option.png');
let selectedPicSourse = require('../../../../imgs/global/success.png');
let searchIcon = require('../../../../imgs/customer/searchLeft.png');
const correct = require('../../../../imgs/global/correct.png');


/*
  chang : 企业变更 特别展示  值: boolean ( true ,false)
  optionBox: 是否显示选项框  值: boolean ( true ,false)
  secondRight:二级目录右边展示类型 值: boolean ( true ,false)
	data : 商品数据  值 : JSON对象
	widthoutTop : 是否展示头部。类型 boolean：true 时不显示头部筛选及操作按钮，默认为false
	renderLeft : 自定义头部-左侧图形。默认 this._renderLeftBtns()
	renderRight : 自定义头部-右侧图形。默认 this._renderRightBtns()
  middleContent : 自定义头部-中间图形。默认 this._renderFilterContent()
  bannerContent: 自定义横幅栏。默认this._renderBannerContent()
  secondRightContent:自定义二级目录右边展示。
	leftBtnsList : 默认头部-左侧按钮。类型obj：{ btnText:'确认添加',btnFun:()=>{console.log(1)}}，不传则不展示
  rightBtnsList : 默认头部-右侧按钮。类型 obj:{ btnText:'确认添加',btnFun:()=>{console.log(1)}}，不传则不展示
  bannerBtnContent:默认中间横幅展示字段。类型 string:''，不传则不展示
  searching:一般搜索的数据没有变化的时候不会触发componentWillReceiveProps函数 status一直等于loading 需要有个变量反馈搜索完毕 值: boolean ( true ,false)
*/


export class ProductCategory extends Component {

  constructor(props) {
    super(props);
    let { data, single, onlyOption, secondRight, secondRightContent, optionBox, showLossInfo, showLogInfo, searching } = this.props;
    this.state = {
      sideDataSource: data || [], // 一级数据
      mainDataSource: data && data[0] && data[0].goodsList || [], // 二级数据
      firstIndex: 0,
      searching: searching || false,
      tabIndex: '0',
      arrAyy: [],
      dataList: [],
      itemData: [],
    }
    this.goodsData = {}; // 参数收集
  }

  componentWillMount () {
  }

  componentWillReceiveProps (props) {
    let { data, onlyOption, searching, optionBox, } = props || {};
    let { tabIndex } = this.state;
    let status;

    if (searching) {
      status = 'loading'
    }
    else {
      status = data && data.length ? 'data' : 'empty'
    }
    this.setState({
      sideDataSource: data || [],
      mainDataSource: data && data[0] && data[tabIndex >= data.length ? 0 : tabIndex].goodsList || [],
      status: status,
    }, () => {
      // let { sideDataSource } = this.state;
      // if (!sideDataSource.length) return;
      // this._sideCheckFn(sideDataSource[tabIndex > sideDataSource.length ? 0 : tabIndex].goodsCateCode);
    })
  }

  //搜索
  _searchFn = () => {
    let { searchPress } = this.props;
    this.setState({
      status: 'loading',
      mainCheckData: [],
      tabIndex: 0,
    }, async () => {
      //获取数据
      let goodsData = searchPress && await searchPress(this.goodsData);
      //根据数据初始化
      // this._formattingData(goodsData, true);
    })
  }

  // 搜索
  _writeFn = async (val) => {
    let searchCode = val
    this.goodsData.searchCode = searchCode;
    this._searchFn();
  }


  //二级勾选
  _checkSecond = (data, index, isbooks) => {
    let { confirmData } = this.props;
    let arr = [];
    let { sideDataSource, mainDataSource, tabIndex, firstIndex, dataList, itemData } = this.state;
    mainDataSource[index].isbooks = !isbooks;
    let isLocks = true;
    let arrAy = [];
    mainDataSource.forEach((item, i) => {
      if (item.isbooks == false) {
        isLocks = false;
      }
    })

    sideDataSource && sideDataSource.forEach((items, j) => {
      items.goodsList.forEach((datas, k) => {
        if (datas.isbooks == true) {
          arrAy.push(datas)
        }
      })
    })
    sideDataSource[tabIndex].isChenckGo = isLocks,
      this.setState({
        mainDataSource,
        sideDataSource,
        dataList: arrAy,
        arrAyy: arr,
      }, () => confirmData && confirmData(arrAy));

  }

  //二级数据
  _renderMain = (data) => {
    const { goodsName,
      teamPid, organLeader, isbooks } = data.item;
    return (

      <View>
        <View style={styles.listMainSelect}>
          <View style={styles.listFlex}>
            <TouchableOpacity style={{ borderColor: '#1660C8', flexDirection: 'row', }}
              onPress={() => this._checkSecond(data, data.index, isbooks)}>
              <View style={styles.lockView}>
                {isbooks ? <Image style={[styles.lockImage, { tintColor: '#1660C8', }]} source={correct} /> : null}
              </View>

              <Text style={styles.listSideTextSelected}>{goodsName}</Text>

            </TouchableOpacity>
          </View>
        </View>
      </View>
    );
  }

  //一级勾选
  _checkFirst = (index, isChenckGo) => {
    let { confirmData } = this.props;
    let { sideDataSource, tabIndex, mainDataSource, dataList } = this.state;
    sideDataSource[index].isChenckGo = !isChenckGo

    // if (tabIndex == index) {
    sideDataSource[index].goodsList.map(item => {
      item.isbooks = !isChenckGo;
    })
    // }
    let arrayys = [];
    // let arrs = [];
    sideDataSource && sideDataSource.forEach((items, i) => {
      // console.log(items, sideDataSource, '99勾选数据')
      if (items.isChenckGo == true) {
        // arrs.push(items)
        items.goodsList.forEach((datas, indexs) => {
          arrayys.push(datas);
        })
      }
    })
    if (isChenckGo == false) {
      this.setState({
        sideDataSource,
        mainDataSource,
        dataList: arrayys || [],
        // itemData: arrs,
      }, () => confirmData && confirmData(arrayys));
    } else {
      this.setState({
        sideDataSource,
        mainDataSource,
        dataList: this.state.sideDataSource[index].goodsList || [],
        // itemData: arrs,
      },
        () => confirmData && confirmData(arrayys)
      );
    }
  }

  // 一级选择
  _sideCheckFn = (data, isChenckGo, i) => {
    let { tabIndex, mainDataSource, sideDataSource } = this.state;
    tabIndex = i;
    mainDataSource = data.item.goodsList;
    this.setState({
      mainDataSource: mainDataSource,
      sideDataSource: sideDataSource,
      tabIndex,
    });
  }
  //一级数据
  _renderSide = (side) => {
    let { goodsCateName, goodsCateCode, goodsList, selected, teamPid, canClaimFlag, organLeader, isChenckGo } = side.item;
    let { tabIndex } = this.state;
    // let curStyle = (selected) ? styles.listSideRowCur : null;
    // let { onlyOption, optionBox } = this.state;
    let cateName = goodsCateName && goodsCateName.length > 5 ? `${goodsCateName.substring(0, 4)}...` : goodsCateName;
    return (
      <View>
        <TouchableOpacity onPress={() => { this._sideCheckFn(side, isChenckGo, side.index) }} activeOpacity={0.5} style={styles.listSideRow}>
          <TouchableOpacity onPress={() => this._checkFirst(side.index, isChenckGo)} style={{ height: '100%', justifyContent: 'center' }}>
            <View style={styles.lockView}>
              {isChenckGo ? <Image style={styles.lockImage} source={correct} /> : null}
            </View>
          </TouchableOpacity>
          <Text style={[styles.listSideTextSelected, tabIndex == side.index ? styles.listSelect : null]}>{cateName}</Text>
          {tabIndex == side.index ? (
            <View style={{
              width: 12 * scale, height: 12 * scale,
              backgroundColor: '#fff', transform: [{ 'rotate': '45deg' }], position: 'absolute', right: -22
            }}></View>
          ) : null}
        </TouchableOpacity>
      </View>

    );
  }
  //头部筛选输入框
  _renderFilterContent () {
    return (
      <TouchableOpacity activeOpacity={1} onPress={() => { this.refs.searchInput.focus() }} style={styles.searchBg}>
        <Image source={searchIcon} style={styles.searchImg} />
        <TextInput
          ref={'searchInput'}
          style={styles.searcuhInput}
          underlineColorAndroid='transparent'
          placeholder={this.props.placeholderText || '请输入三级'}
          onChangeText={(value) => {
            this._writeFn(value);
          }}
          returnKeyType={'search'}
        />
      </TouchableOpacity>
    )
  }
  //头部左测自定义框
  _renderLeftBtns () {
    let { leftBtnsList } = this.props;
    return (
      <View style={productSelectStyle.topBtns}>
        {
          leftBtnsList ?
            <View style={productSelectStyle.topBtns}>
              <Text style={productSelectStyle.topBtnText} onPress={leftBtnsList.btnFun} >{leftBtnsList.btnText}</Text>
              <TouchableOpacity onPress={leftBtnsList.iconFun} >
                <Image source={leftBtnsList.iconImg} style={productSelectStyle.topBtnIcon} />
              </TouchableOpacity>
            </View>
            : null}
      </View>
    )
  }
  //头部和底部之间横幅栏自定义框
  _renderbannerContent () {
    let { bannerBtnContent } = this.props;
    return (
      <View style={styles.bannerBox}>
        {
          bannerBtnContent ?
            <Text style={styles.bannerText}>{bannerBtnContent}</Text>
            : null
        }
      </View >
    )
  }
  btnFun = () => {

  }
  //头部右测自定义框
  _renderRightBtns () {
    let { rightBtnsList } = this.props;
    return (
      <View style={styles.topBtns}>
        {
          rightBtnsList && rightBtnsList.length ?
            rightBtnsList.map((item, index) => {
              return (
                <Text key={index} style={styles.topBtnText} onPress={() => { item.btnFun(this.state.sideDataSource, this.state.dataList) }}>{item.btnText}</Text>
              )
            }) : null
        }
      </View>
    )
  }

  render () {
    let { sideDataSource, mainDataSource, status, } = this.state;
    return (
      <View style={styles.containerModal}>
        <View style={styles.searchBox}>
          {
            this._renderFilterContent()
          }
          {this._renderRightBtns()}
        </View>
        <View style={styles.listView}>
          {(sideDataSource && sideDataSource.length > 0) ? (
            <View style={{ flexDirection: 'row' }}>
              <View style={styles.listSideWrap}>
                <FlatList
                  extraData={this.state}
                  style={styles.listSideView}
                  data={sideDataSource}
                  renderItem={this._renderSide}
                />
              </View>
              <ScrollView
                horizontal={true}
                style={styles.listMainWrap}>
                {
                  (mainDataSource && mainDataSource.length > 0) ? (
                    <FlatList
                      extraData={this.state}
                      style={styles.listMainView}
                      data={mainDataSource}
                      renderItem={this._renderMain}
                    />) : (
                      <View style={{ width: 255 * scale, height: '70%' }}>
                        <PageStatusIndex status={'empty'} emptyText={'该类目暂时无子商品'} />
                      </View>
                    )
                }
              </ScrollView>
            </View>
          ) : (<View style={{ flex: 1, height: '70%' }}>
            <PageStatusIndex status={status} emptyText={'暂无品类'} />
          </View>)}
        </View>
      </View>
    )
  }
}


const styles = StyleSheet.create({
  topBtns: {
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row'
  },
  listSelect: {
    color: style.color.themeColor,
  },
  topBtnText: {
    fontSize: 12 * scale,
    fontWeight: 'bold',
    color: style.color.themeColor,
    paddingLeft: 12 * scale,
    paddingRight: 10 * scale,
  },
  topBtnIcon: {
    width: 12 * scale,
    height: 12 * scale,
    // margin: 4 * scale
  },
  containerModal: {
    width: 375 * scale,
    backgroundColor: '#fff',
    borderRadius: 15 * scale,
    flex: 1
  },
  listHead: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    height: 52 * scale,
    width: 375 * scale,
    alignItems: 'center',
  },
  listHeadText: {
    fontSize: 16 * scale,
    color: style.color.themeColor,
    paddingTop: 5 * scale,
    paddingBottom: 5 * scale,
    paddingLeft: 8 * scale,
    paddingRight: 8 * scale
  },
  listView: {
    flex: 1,
    flexDirection: 'row',
    borderTopColor: '#F4F7FE',

  },
  listSideWrap: {
    paddingLeft: 20 * scale,
    backgroundColor: '#F4F7FE',
  },
  listSideView: {
    width: 116 * scale,
  },
  listSideRow: {
    height: 50 * scale,
    width: 100 * scale,
    alignItems: 'center',
    flexDirection: 'row',
  },
  listSideRowCur: {
    backgroundColor: '#fff',
  },
  listSideTextSelected: {
    fontSize: 14 * scale,
    color: '#000000',
    fontWeight: 'bold'
  },
  listSideText: {
    fontSize: 14 * scale,
    color: '#000000',
  },
  longText: {
    fontSize: 13 * scale,
    color: '#8B8B8B',
    width: 160 * scale
  },
  listMainWrap: {
    paddingBottom: 20 * scale,
    backgroundColor: '#fff',
    width: 255 * scale,
  },
  listMainView: {
    width: 255 * scale,
    paddingLeft: 2 * scale,
    paddingRight: 20 * scale,
    backgroundColor: '#fff'
  },
  listMainRow: {
    flexDirection: 'row',
    paddingTop: 10 * scale,
    paddingBottom: 10 * scale,
    paddingLeft: 10 * scale,
    justifyContent: 'space-between',
    alignItems: 'center'
  },
  listMainSelect: {
    flexDirection: 'row',
    paddingTop: 10 * scale,
    paddingBottom: 10 * scale,
    paddingLeft: 10 * scale,
    justifyContent: 'space-between',
  },
  optionPic: {
    width: 14 * scale,
    height: 14 * scale,
    marginLeft: 10 * scale,
    marginRight: 10 * scale
  },
  searchBox: {
    paddingTop: 13 * scale,
    paddingBottom: 5 * scale,
    flexDirection: 'row',
    alignItems: 'center',
  },
  searchBg: {
    flex: 1,
    backgroundColor: '#F4F7FE',
    borderRadius: 4 * scale,
    paddingTop: 8 * scale,
    paddingBottom: 8 * scale,
    paddingLeft: 12 * scale,
    paddingRight: 12 * scale,
    marginLeft: 12 * scale,
    marginRight: 12 * scale,
    flexDirection: 'row',
    alignItems: 'center',
  },
  searchBtn: {
    fontSize: 12 * scale,
    color: style.color.themeColor,
    marginLeft: 10 * scale,
    padding: 5 * scale
  },
  searchImg: {
    width: 11 * scale,
    height: 11 * scale,
  },
  searcuhInput: {
    paddingVertical: 0,
    height: 18 * scale,
    fontSize: 12 * scale,
    paddingLeft: 20 * scale,
    width: 170 * scale,
  },
  selectNumber: {
    borderRadius: 5 * scale,
    width: 20 * scale,
    height: 14 * scale,
    marginLeft: 5 * scale,
    fontSize: 11 * scale,
    backgroundColor: style.color.themeColor,
    color: style.color.white,
    textAlign: 'center'
  },
  tips: {
    width: 15 * scale,
    height: 15 * scale,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    borderWidth: 1 / PixelRatio.get(),
    borderStyle: 'solid',
    borderRadius: 2 * scale,

  },
  tipsText: {
    fontSize: 10 * scale
  },
  changeText: {
    color: style.color.fontRed1,
    fontSize: 12 * scale,
    paddingLeft: 5 * scale
  },
  lockView: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    height: 12 * scale,
    width: 12 * scale,
    borderWidth: 1 * scale,
    borderColor: '#1660C8',
    marginLeft: 14 * scale,
    marginRight: 10 * scale,
  },
  lockImage: {
    width: 8 * scale,
    height: 6 * scale,
    tintColor: '#99C2EB',
  },
  listFlex: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    // alignItems: 'center'
  },
  bannerBox: {
    paddingLeft: 10 * scale,
    paddingTop: 5 * scale,
    paddingBottom: 10 * scale
  },
  bannerText: {
    color: '#F00707',
    fontSize: 12
  },
  applyStaffName: {
    fontSize: 10 * scale,
    color: '#7F7F7F',
    marginTop: 7 * scale
  },
  applyStaffNameNO: {
    fontSize: 10 * scale,
    color: '#7F7F7F',
    marginTop: 7 * scale,
    marginLeft: 15 * scale
  },
  lossDateText: {
    fontSize: 10 * scale,
    color: '#E02020',
    marginRight: 5 * scale
  },
  approveLogText: {
    fontSize: 10 * scale,
    color: style.color.themeColor,
  },
  auditingText: {
    alignSelf: 'center',
    color: '#F7B500',
    fontSize: 10 * scale,
    marginTop: 7 * scale
  }
})